package com.comleader.operator.controller;

import static com.comleader.operator.common.constant.Constant.BATCH_SIZE;
import static com.comleader.operator.pojo.entity.table.PersonalUserTableDef.PERSONAL_USER;
import static com.comleader.operator.validate.CommonValidator.isAddressNoncompliant;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.comleader.operator.common.constant.GlobalVariables;
import com.comleader.operator.common.util.ExcelUtil;
import com.comleader.operator.pojo.entity.DictDataEntity;
import com.comleader.operator.service.DictDataService;
import com.comleader.operator.validate.CommonValidator;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.comleader.operator.common.util.OperatorObjectUtil;
import com.comleader.operator.pojo.entity.PersonalUserEntity;
import com.comleader.operator.pojo.entity.SysConfigEntity;
import com.comleader.operator.service.PersonalUserService;
import com.comleader.operator.service.SysConfigService;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;

/**
 * @Dscription
 * @Author 连新景
 * @Date 2023/7/4 11:38
 */
@Slf4j
@RequestMapping("/test")
@RestController
public class HeheController {

    /*   @Resource
    private OutboundRecordService outboundRecordService;*/

    // @Transactional(rollbackFor = Exception.class)
    /*@RequestMapping("/save")
    public void save() throws InterruptedException {
        List<OutboundRecord> list = new ArrayList<>(1000000);
    
        for (int i = 0; i < 1000000; i++) {
            OutboundRecord outboundRecord = new OutboundRecord();
            outboundRecord.setCaller("123456" + i);
            outboundRecord.setCallerHomeProvince("河南");
            outboundRecord.setCallerHomeCity("郑州");
            outboundRecord.setCalled("110");
            outboundRecord.setCalledHomeProvince("广东");
            outboundRecord.setCalledHomeCity("深圳");
            outboundRecord.setCallStartTime(LocalDateTime.now());
            outboundRecord.setCallEndTime(LocalDateTime.now().plusDays(1));
            outboundRecord.setCallDuration(666);
            outboundRecord.setTypeSource(0);
            outboundRecord.setDatasourceId("dsdadada");
            outboundRecord.setBacktrackId(888L);
            outboundRecord.setOutboundReason("不外呼了");
            outboundRecord.setState(CommonStateEnum.DISABLE);
            outboundRecord.setCreateTime(LocalDateTime.now());
            outboundRecord.setUpdateTime(LocalDateTime.now());
            list.add(outboundRecord);
        }
        *//* OutboundRecord  outboundRecord = new OutboundRecord();
             outboundRecord.setCaller("1111111111111111111111111111111111111111111111111111111111111111111111");
             list.add(outboundRecord);
             
             
             
             
             
             outboundRecord = new OutboundRecord();
             outboundRecord.setCaller("33333333333333333333333333333333333333333333333333333333333333333333333");
             list.add(outboundRecord);*//*
                                           int totalPage = PageUtil.totalPage(1000000, 10000);
                                           StopWatch stopWatch = new StopWatch();
                                           stopWatch.start();
                                           ThreadPoolExecutor threadPoolExecutor =
                                           ThreadUtil.newExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors() + 1);
                                           CountDownLatch countDownLatch = new CountDownLatch(100);
                                           System.out.println("开始插入");
                                           for (int i = 0; i < totalPage; i++) {
                                           List<OutboundRecord> hehe = ListUtil.page(i, 10000, list);
                                           threadPoolExecutor.execute(() -> {
                                           // outboundRecordService.getMapper().insertBatch(hehe);
                                           outboundRecordService.saveBatch(hehe, 10000);
                                           countDownLatch.countDown();
                                           });
                                           
                                           }
                                           // outboundRecordService.saveBatch(list);
                                           countDownLatch.await();
                                           *//*  Db.executeBatch(list, 10000,OutboundRecordMapper.class,(mapper, outboundRecord2)->{
                                                  mapper.insert(outboundRecord2);
                                                });*//*
                                                        // outboundRecordService.saveBatch(list,100000);
                                                        *//*   for (int i = 0; i < totalPage; i++) {
                                                               List<OutboundRecord> hehe=ListUtil.page(i,1000,list);
                                                                   outboundRecordService.getMapper().insertBatch(hehe);
                                                             }*//*
                                                                   stopWatch.stop();
                                                                   System.out.println("总耗时：" + stopWatch.getTotalTimeSeconds());
                                                                   
                                                                   *//*  Db.tx(()->{
                                                                          Db.executeBatch(list, OutboundRecordMapper.class,(mapper,outboundRecord2)->{
                                                                              mapper.insert(outboundRecord2);
                                                                          });
                                                                          return true;
                                                                        });*//*
                                                                                }*/

    /*  @RequestMapping("/select/{id}")
    public OutboundRecord select(@PathVariable Long id) {
        Optional<OutboundRecord> outboundRecordDO = outboundRecordService.getByIdOpt(id);
    
        outboundRecordDO.ifPresent(hehe -> {
            System.out.println(JSONUtil.toJsonStr(hehe));
        });
    
        QueryWrapper queryWrapper = QueryWrapper.create().select().where(OUTBOUND_RECORD.ID.eq(1));
        OutboundRecord data = outboundRecordService.getOne(queryWrapper);
        System.out.println(data);
        return data;
    }*/

    @Resource
    private PersonalUserService personalUserService;

    @Resource
    private SysConfigService sysConfigService;

    @Resource
    private DictDataService dictDataService;

    @SaIgnore
    @RequestMapping("/hehe")
    public void hehe(String data) {
        /* DictCacheUtil.getDictCache("hehe");
        // PersonalUserValidator.isDictIncorrect("hehe","111");
        List<PersonalUserEntity> psrsonalMobileList = personalUserService.listByTypeAndName(PERSON_USER, MOBILE_PHONE, PERSONAL_USER.OWNER_ID_NUMBER, PERSONAL_USER.OWNER_NAME);
        List<PersonalUserEntity> oneCardFiveNumbersList = personalUserService.listOneCardFiveNumbers();
        ThreadUtil.execute(()->{
          int a=2/0;
        
        });*/
        SysConfigEntity sysConfigEntity = sysConfigService.selectByKey(data);
        String value = Optional.ofNullable(sysConfigEntity).orElse(new SysConfigEntity()).getParamValue();
        System.out.println(value);

        List<DictDataEntity> dictDataEntityList= dictDataService.listDictDataByCode("customer_type");
        Console.log(dictDataEntityList);

        Map<Integer, List<String>> map= GlobalVariables.getTypeCodeMap();
        Console.log(map);
        System.out.println(isAddressNoncompliant("郑州市金水区马头岗新城2号楼1单元","郑州市金水区马头岗新城2号楼1单元"));
        List<String> list=new ArrayList<>(50000);
        for (int i = 0; i < 50000; i++) {
            list.add("1371234567"+i);
        }
        QueryWrapper queryWrapper=QueryWrapper.create().where(PERSONAL_USER.USER_NUMBER.in(list));
        personalUserService.list(queryWrapper);
    }

    public static void main(String[] args) throws IOException, IllegalAccessException {
        String line;
        List<String> filedList;
        BufferedReader reader = FileUtil.getUtf8Reader(new File("./importFile/个人用户实名制499999.txt"));
        List<PersonalUserEntity> list = new ArrayList<>(500000);
        int lineNum=1;
        while (true) {
            line = reader.readLine();
            if (StrUtil.isBlank(line)) {
                break;
            }
            filedList = StrUtil.split(line, "||");
            PersonalUserEntity personalUser = OperatorObjectUtil.createObj(filedList, PersonalUserEntity.class);
            personalUser.setLineNum(lineNum++);
            list.add(personalUser);
        }
        //ExcelUtil.writeOneSheetRepeat("./reportFile/666888/hehe2.xlsx",PersonalUserEntity.class,"hehe",list);
      /*  ExcelWriter excelWriter= ExcelUtil.getBigWriter(new File("./reportFile/666888/hehe2.xlsx"));
        excelWriter.setOnlyAlias(true);
        excelWriter.write(list,true);
        excelWriter.close();
        System.out.println(list.size());*/
        Workbook workbook=new SXSSFWorkbook(10000);
        Sheet sheet=workbook.createSheet("xixi");
        Field[] fields= PersonalUserEntity.class.getDeclaredFields();
        for (int i = 0; i < list.size(); i++) {
            Row row=sheet.createRow(i);
            PersonalUserEntity personalUser=list.get(i);
            for (int j = 2; j < fields.length; j++) {
                Cell cell=row.createCell(j-2);
                fields[j].setAccessible(true);
                cell.setCellValue((String) fields[j].get(personalUser));
            }
            if(i%1000==0){
                ((SXSSFSheet)sheet).flushRows(1000);
            }
        }
        FileOutputStream fileOutputStream=new FileOutputStream("./reportFile/666888/luluna.xlsx");
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        ((SXSSFWorkbook)workbook).dispose();
        System.out.println("已结束");

    }

    @SaIgnore
    @RequestMapping("/haha")
    public void haha(HttpServletRequest request, HttpSession session) {

        log.info("sessionId:{}",session.getId());
        log.info("sessionId:{}",request.getSession().getId());
        DictDataEntity dictData=new DictDataEntity();
        dictData.setId(0);
        dictData.setCode("666");
        dictData.setDictKey("hehe");
        dictData.setDictValue("888");
        dictData.setSort(0);

        session.setAttribute("name",dictData);
     /*   System.out.println(CommonValidator.isDateFormatException(null, DatePattern.PURE_DATE_FORMATTER));
        System.out.println(CommonValidator.isDateFormatException("2024091", DatePattern.PURE_DATE_FORMATTER));
        System.out.println(CommonValidator.isDateFormatException("20240911", DatePattern.PURE_DATE_FORMATTER));
        List list=ListUtil.of(1,2,3);
        System.out.println(list.contains(null));*/

    }

    @SaIgnore
    @RequestMapping("/xixi")
    public void hehe() {
        try{
            ThreadUtil.execute(()->{

               try{
                   String hehe="dsdsds";
                   int a=2/0;
                   int b=1*2;
               } catch (Exception e){
                   log.info("异常了22222",e);

               }
            });
        }catch (Exception e){
            log.info("异常了",e);
        }

    }

    @SaIgnore
    @RequestMapping("/getSession")
    public void getSession(HttpServletRequest request, HttpSession session) {

        log.info("sessionId:{}",session.getId());
        log.info("sessionId:{}",request.getSession().getId());
        DictDataEntity dictData=(DictDataEntity)session.getAttribute("name");
        log.info(JSONUtil.toJsonStr(dictData));
     /*   System.out.println(CommonValidator.isDateFormatException(null, DatePattern.PURE_DATE_FORMATTER));
        System.out.println(CommonValidator.isDateFormatException("2024091", DatePattern.PURE_DATE_FORMATTER));
        System.out.println(CommonValidator.isDateFormatException("20240911", DatePattern.PURE_DATE_FORMATTER));
        List list=ListUtil.of(1,2,3);
        System.out.println(list.contains(null));*/

    }
}
